//
//  URLLoader.m
//  testXMLParse
//
//  Created by Yang Song on 12/6/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "URLLoader.h"


@implementation URLLoader

@synthesize delegate;
@synthesize responseData;
@synthesize urlAddress;


-(void)dealloc{
    [responseData release];
    [urlAddress release];
    [super dealloc];
}

-(void)loadUrl:(NSString*)httpURL withDelegate:(id)aDelegate;{
	self.delegate=aDelegate;
	self.urlAddress=httpURL;
    
    //url encode
    NSString* escapedUrlString =[httpURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    
	NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
	_connection=[[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
}

-(void)cancelLoading{
    self.responseData=nil;
    [_connection cancel];
}

#pragma mark NSURLConnection delegate method

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.responseData = [NSMutableData data];    // start off with new data
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];  // append incoming data
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"didFailWithError%@",error);
	if ((nil!=delegate)&&[delegate respondsToSelector:@selector(receiveDataFailedWithError:withURL:)]){
		if ([error code] == kCFURLErrorNotConnectedToInternet)
		{
			// if we can identify the error, we can present a more precise message to the user.
			NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
																 forKey:NSLocalizedDescriptionKey];
			NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
															 code:kCFURLErrorNotConnectedToInternet
														 userInfo:userInfo];
			[delegate receiveDataFailedWithError:noConnectionError withURL:self.urlAddress];
		}
		else
		{
			// otherwise handle the error generically
			[delegate receiveDataFailedWithError:error  withURL:self.urlAddress];
		}
	}
    _connection=nil;
}

// -------------------------------------------------------------------------------
//	connectionDidFinishLoading:connection
// -------------------------------------------------------------------------------
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"connectionDidFinishLoading");
	if ((nil!=delegate)&&[delegate respondsToSelector:@selector(receivedData:withURL:)]){
		[delegate receivedData:responseData withURL:self.urlAddress];
	}
    // ownership of appListData has been transferred to the parse operation
    // and should no longer be referenced in this thread
    self.responseData = nil;
    _connection=nil;
}

@end
